//
//  VipViewController.m
//  Medgretraining
//
//  Created by 辰领科技 on 16/5/17.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "VipViewController.h"
#import "VipTableViewCell.h"
#import "PayTypeViewController.h"
static NSString * CellIndentfier = @"VipTableViewCell";
@interface VipViewController ()<BestScrollViewDelegate,BestScrollViewDatasource,UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *rechrages;
@property (nonatomic,strong)  BestScrollView *headerScroll;//滚动栏
@property (nonatomic,strong)  NSMutableArray  *imageArray;

@end

@implementation VipViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _imageArray = [NSMutableArray array];
    _rechrages = [NSMutableArray array];
    [self initViewLayout];
    [self getAdvertiseBanner];
    [self getRechargeList];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    
    
    _scroView.frame = CGRectMake(0, 64* VerticalRatio(), 320* VerticalRatio(), 504* VerticalRatio()-49);
    _scroView.contentSize = flexibleSize(CGSizeMake(0, 504* VerticalRatio()-48), NO);
    
    //广告栏
    _headerScroll=[[BestScrollView alloc]  initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 123), NO)];
    [self.scroView addSubview:_headerScroll];
    
    [self.tableView registerNib:[UINib nibWithNibName:CellIndentfier bundle:nil] forCellReuseIdentifier:CellIndentfier];

    
}



#pragma mark  获取首页广告BANNER--=========================================
-(void)getAdvertiseBanner{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"2" forKey:@"Id"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_kADBannerTag withHttpType:@"POST" withTag:HK_HK_kADBannerTag];
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getRechargeList];
        });
    }];
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.rechrages.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getRechargeList];
        });
    }
    
}


- (void)getRechargeList{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[NSNumber numberWithInt:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInt:PageSize] forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_queryMallEpurse withHttpType:@"POST" withTag:HK_HK_queryMallEpurse];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView  heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 56*VerticalRatio();
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _rechrages.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    VipTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentfier];
    if (cell == nil) {
        cell= [[VipTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentfier];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
        NSDictionary * dic = _rechrages[indexPath.row];

        cell.rechargeMoney.text = [NSString stringWithFormat:@"充值%@元",dic[@"mepuRealMoney"]];
        cell.presentMoney.text = [NSString stringWithFormat:@"额外赠送%@元",dic[@"mepuLabelMoney"]];
    cell.rechargeBlock = ^(){
 
        if (![Common getLoginStatus]) {
            [[AppDelegate sharedAppDelegate]ShowLoginPage];
            return ;
        }
               NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
        [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
        [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
        [dic setObject:_rechrages[indexPath.row][@"mepuId"] forKey:@"mepuId"];
      
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:HK_saveMemberEpurseOrder withHttpType:@"POST" withTag:HK_HK_saveMemberEpurseOrder];

    };
    
    return cell;
    
    
}


#pragma  mark BestView Delegate Data=source=====================


- (NSInteger)numberOfPagesatView:(BestScrollView *)bsView
{
    
    return  self.imageArray.count;
    
}

- (UIView *)pageAtIndex:(NSInteger)index atView:(BestScrollView *)bsView
{
    
    if (self.imageArray.count>0) {
        
        UIImageView  *imageView=[[UIImageView alloc]  initWithFrame: flexibleFrame(CGRectMake(0, 0, 320, 140), NO)];
        [imageView  sd_setImageWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,_imageArray[index][@"titleimg"]]] placeholderImage:[UIImage imageNamed:@"integral2"]];
        return imageView;
    }
    return nil;
}


- (void)didClickPage:(BestScrollView *)csView atIndex:(NSInteger)index
{
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==HK_HK_kADBannerTag) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            self.imageArray = database[@"result"];
            
            self.headerScroll.delegate=self;
            self.headerScroll.datasource=self;
            [self.headerScroll showImageArray:self.imageArray   withAnimation:YES];
        }
        
    }else if (tag==HK_HK_queryMallEpurse) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {

            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.rechrages removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.rechrages addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
            });
            
        }
        
    }else if (tag==HK_HK_saveMemberEpurseOrder) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"IndentsStoryboard" bundle:nil];
            PayTypeViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"PayType"];
            page.payOrderPrice = database[@"result"][@"meorAmount"];
            page.payOrderName = @"充值有礼";
            page.payId = database[@"result"][@"meorNo"];
            page.payTypes = @"2";
            [[Common getNavigation]pushViewController:page];
        
        }
    }
}


-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
            //
            [self dismissWaitDialog];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
